package com.wnxy.sddfp.search.service.impl;
import com.google.common.collect.Lists;

import com.wnxy.sddfp.common.model.page.PageVo;
import com.wnxy.sddfp.search.model.query.BorrowRecordSearchQuery;
import com.wnxy.sddfp.search.model.vo.BorrowRecordIndexVo;
import com.wnxy.sddfp.search.service.SearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public PageVo<BorrowRecordIndexVo> search(BorrowRecordSearchQuery params) {
        // 条件构造器
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        // 构造条件
        if (StringUtils.hasText(params.getName())) {
            builder.withQuery(QueryBuilders.matchQuery("name", params.getName()));
        }
        if (StringUtils.hasText(params.getDescription())) {
            builder.withQuery(QueryBuilders.matchQuery("description", params.getDescription()));
        }
        if (params.getStartPeriod() != null) {
            builder.withQuery(QueryBuilders.rangeQuery("period").gte(params.getStartPeriod()));
        }
        if (params.getEndPeriod() != null) {
            builder.withQuery(QueryBuilders.rangeQuery("period").lte(params.getEndPeriod()));
        }
        // 分页
        builder.withPageable(PageRequest.of(params.getPageNo() - 1,params.getPageSize()));
        // 排序
        builder.withSort(SortBuilders.fieldSort("createdate").order(SortOrder.DESC));
        // 查询
        SearchHits<BorrowRecordIndexVo> searchHits =
                elasticsearchRestTemplate.search(builder.build(), BorrowRecordIndexVo.class);
        List<BorrowRecordIndexVo> voList = searchHits.getSearchHits().stream()
                .map(SearchHit::getContent).collect(Collectors.toList());

        PageVo<BorrowRecordIndexVo> pageVo = new PageVo<>();
        pageVo.setList(voList);
        pageVo.setTotal(searchHits.getTotalHits());
        pageVo.setPageNum(params.getPageNo());
        pageVo.setPageSize(params.getPageSize());
        return pageVo;
    }
}
